package com.example.handle.common;

import com.example.pojo.vo.common.Result;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2022/7/14 10:24
 */
public class MyHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
    private HandlerMethodReturnValueHandler handler;

    public MyHandlerMethodReturnValueHandler(HandlerMethodReturnValueHandler handler) {
        this.handler = handler;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return handler.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest) throws Exception {

        if (isBaseResult(returnValue)) {
            handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
        } else {
            handler.handleReturnValue(Result.OK(returnValue), returnType, mavContainer, webRequest);
        }
    }

    private boolean isBaseResult(Object returnValue) {

        return returnValue instanceof Result;
    }
}
